//
//  SinaWeiboSDK.m
//  MrWrite
//
//  Created by lilg on 13-7-24.
//  Copyright (c) 2013年 Founder. All rights reserved.
//

#import "SinaWeiboSDK.h"
#import "SinaAuthorizeView.h"
#import "ASIFormDataRequest.h"
#import "SinaWeiBoAPI.h"
#import "JSONKit.h"

@interface SinaWeiboSDK ()<SinaAuthorizeDelegate,ASIHTTPRequestDelegate>

@end

@implementation SinaWeiboSDK
@synthesize delegate;
@synthesize uid;
@synthesize accessToken;
@synthesize expirationDate;


#pragma mark -SSO认证回调函数
+ (BOOL)HandleOpenURL:(NSURL *)url
{
  NSString *urlStr =[url absoluteString];
  if ([urlStr hasPrefix:@"sinaweibosso"])
  {
    NSRange  user_cancelledRange = [urlStr rangeOfString:@"user_cancelled="];
    if (user_cancelledRange.length!=0)
    {
      return NO;
    }
    SinaWeiboSDK *sdk = [[SinaWeiboSDK alloc]init];
    NSArray   *tmpArr = [urlStr componentsSeparatedByString:@"&"];
    for (NSString  *string  in tmpArr)
    {
      NSRange  expires_inRange = [string rangeOfString:@"expires_in="];
      if (expires_inRange.length!=0)
      {
        NSString  *expires_in = [string substringFromIndex:expires_inRange.location+expires_inRange.length];
        NSTimeInterval  expirationTime = [[NSDate date]timeIntervalSince1970]+[expires_in doubleValue];
        sdk.expirationDate = [NSDate dateWithTimeIntervalSince1970:expirationTime];
      }
      NSRange  uidRange = [string rangeOfString:@"uid="];
      if (uidRange.length!=0) sdk.uid = [string substringFromIndex:uidRange.location+uidRange.length];
      NSRange  access_tokenRange = [string rangeOfString:@"access_token="];
      if (access_tokenRange.length!=0) sdk.accessToken =[string substringFromIndex:access_tokenRange.location+access_tokenRange.length];
    }
    if (sdk.accessToken&& 0 != [sdk.accessToken length])
    {
      //记录登陆后的数据信息
      NSMutableDictionary *oauthDic = [[NSMutableDictionary alloc]init];
      [oauthDic setObject:sdk.accessToken forKey:SINA_AccessToken];
      [oauthDic setObject:sdk.expirationDate forKey:SINA_ExpirationDate];
      [oauthDic setObject:sdk.uid forKey:SINA_Uid];
      [[NSUserDefaults standardUserDefaults]setObject:oauthDic forKey:SINA_OAuth];
      [oauthDic release];
    }
    if ([[ShareManger SharedInstance] respondsToSelector:@selector(SinaWeiboDidLogin:)]) {
      [[ShareManger SharedInstance]SinaWeiboDidLogin:sdk];
    }
    [sdk release];
    return YES;
  }
  else return NO;
}


-(id)initWithFrame:(CGRect)frame andAppKey:(NSString *)appkey andAppSecret:(NSString *)appSecret andRedirectURI:(NSString *)redirectURI  delegate:(id<SinaWeiboDelegate>)weiBodelegate;
{
    self = [super initWithFrame:frame];
    if (self) {
      self.delegate = weiBodelegate;
      _appKey = appkey;
      _appSecret = appSecret;
      _redirectURI = redirectURI;
    }
    return self;
}

#pragma mark -获取新浪授权，不支持sso则调用web认证
-(void)SinaStartAuthorize
{
  if (![self CanSSOAuthentication])
  {
    SinaAuthorizeView *webView = [[SinaAuthorizeView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) andAppKey:_appKey andAppSecret:_appSecret andRedirectURI:_redirectURI delegate:self];
     [webView ShowWebView];
      [webView release];
  }
}

#pragma mark－判断是否在有效期限内
-(BOOL)isSessionValid
{
    NSDictionary  *SinaOAuthDic = [NSDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults]objectForKey:@"SinaOauth"]];
    if (SinaOAuthDic)
    {
      self.accessToken = [SinaOAuthDic objectForKey:@"accesstoken"];
      self.expirationDate = [SinaOAuthDic objectForKey:@"expirationDate"];
      self.uid = [SinaOAuthDic objectForKey:@"uid"];
      return (self.accessToken != nil && self.expirationDate != nil && self.uid != nil && NSOrderedDescending == [self.expirationDate compare:[NSDate date]]);
    }
    else return NO;
}

#pragma mark -授权回收
-(void)SinaLoginOut
{
  NSDictionary  *SinaOAuthDic = [[NSUserDefaults standardUserDefaults]objectForKey:SINA_OAuth];
  NSString *revokeoauthStr =SinaRevokeoauth([SinaOAuthDic objectForKey:SINA_AccessToken]);
  NSURL *revokeoauthURL = [NSURL URLWithString:[revokeoauthStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  ASIHTTPRequest *revokRequest = [ASIHTTPRequest requestWithURL:revokeoauthURL];
  [revokRequest setRequestMethod:@"POST"];
  [revokRequest setValidatesSecureCertificate:YES];
  [revokRequest startSynchronous];
  NSString * response = [[NSString alloc] initWithData:[revokRequest responseData] encoding:NSUTF8StringEncoding];
    NSData* jsonData = [response dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseDic = [jsonData objectFromJSONData];
    [response release];
  if ([[responseDic objectForKey:@"result"]boolValue]) {
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:SINA_OAuth];
    if ([self.delegate respondsToSelector:@selector(SinaWeiboDidLoginOut)]) {
      [delegate SinaWeiboDidLoginOut];
    }
  }
}
#pragma mark -SSO授权认证
-(BOOL)CanSSOAuthentication
{
  BOOL ssoLoggingIn = NO;
  NSString *ssoCallbackScheme = [NSString stringWithFormat:@"sinaweibosso.%@://",_appKey];
  UIDevice *device = [UIDevice currentDevice];
  if ([device respondsToSelector:@selector(isMultitaskingSupported)] &&
      [device isMultitaskingSupported])
  {
    NSDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                            _appKey, @"client_id",
                            _redirectURI, @"redirect_uri",
                            ssoCallbackScheme, @"callback_uri", nil];
    // 先用iPad微博打开
    NSString *appAuthBaseURL = @"sinaweibohdsso://login";
    if ([self SinaWeiboIsDeviceIPad])
    {
      NSString *appAuthURL = [self serializeURL:appAuthBaseURL
                                         params:params httpMethod:@"GET"];
      ssoLoggingIn = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appAuthURL]];
    }
    // 在用iPhone微博打开
    if (!ssoLoggingIn)
    {
      appAuthBaseURL = @"sinaweibosso://login";
      NSString *appAuthURL = [self serializeURL:appAuthBaseURL
                                         params:params httpMethod:@"GET"];
      ssoLoggingIn = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appAuthURL]];
    }
  }
  return ssoLoggingIn;
}

-(NSString *)serializeURL:(NSString *)baseURL params:(NSDictionary *)params httpMethod:(NSString *)httpMethod
{
  NSURL* parsedURL = [NSURL URLWithString:baseURL];
  NSString* queryPrefix = parsedURL.query ? @"&" : @"?";
  NSMutableArray* pairs = [NSMutableArray array];
  for (NSString* key in [params keyEnumerator])
  {
    if (([[params objectForKey:key] isKindOfClass:[UIImage class]])
        ||([[params objectForKey:key] isKindOfClass:[NSData class]]))
    {
      if ([httpMethod isEqualToString:@"GET"])
      {
        NSLog(@"can not use GET to upload a file");
      }
      continue;
    }
    
    NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(
                                                                                  NULL, /* allocator */
                                                                                  (CFStringRef)[params objectForKey:key],
                                                                                  NULL, /* charactersToLeaveUnescaped */
                                                                                  (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                  kCFStringEncodingUTF8);
    [pairs addObject:[NSString stringWithFormat:@"%@=%@", key, escaped_value]];
    [escaped_value release];
  }
  NSString* query = [pairs componentsJoinedByString:@"&"];
  return [NSString stringWithFormat:@"%@%@%@", baseURL, queryPrefix, query];
}

-(BOOL)SinaWeiboIsDeviceIPad
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
  if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  {
    return YES;
  }
#endif
  return NO;
}


#pragma mark 分享新浪微博
-(void)shareThread:(NSArray *)_array
{
  if ([self isSessionValid]) {
    [NSThread detachNewThreadSelector:@selector(share:) toTarget:self withObject:_array];
  }
  else
  {
    UIAlertView *action = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请绑定新浪微博帐号" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [action show];
    [action release];
  }
}

-(void)share:(NSArray *)_array
{
  if (_array.count==1)
  {
    [self shareWeibo:[_array objectAtIndex:0] withImage:nil withPicUrl:nil];
    
  }else if ([[_array objectAtIndex:1]isKindOfClass:[UIImage class]])
  {
    [self shareWeibo:[_array objectAtIndex:0] withImage:[_array objectAtIndex:1] withPicUrl:nil];
  }else
  {
    [self shareWeibo:[_array objectAtIndex:0] withImage:nil withPicUrl:[_array objectAtIndex:1]];
  }
}

-(void)shareWeibo:(NSString *)_text withImage:(UIImage *)_image withPicUrl:(NSString *)_picurl
{
  NSDictionary *oauthDic = [[NSUserDefaults standardUserDefaults] objectForKey:SINA_OAuth];
  NSString *token = [oauthDic objectForKey:SINA_AccessToken];
  NSString *thisUrl;
  if (_image!=nil)
  {
    //图片
    thisUrl = [NSString stringWithFormat:@"https://upload.api.weibo.com/2/statuses/upload.json?access_token=%@",token];
  }else if(_picurl!=nil)
  {
    //图片url
    thisUrl = [NSString stringWithFormat:@"https://api.weibo.com/2/statuses/upload_url_text.json?access_token=%@&url=%@",token,_picurl];
  }else
  {
    //文字
    thisUrl = [NSString stringWithFormat:@"https://api.weibo.com/2/statuses/update.json?access_token=%@",token];
  }
  
  NSURL *url = [NSURL URLWithString:[thisUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:url];
  [request setRequestMethod:@"POST"];
    request.delegate = self;
  [request setValidatesSecureCertificate:YES];
  [request setPostValue:_text forKey:@"status"];
  if (_image!=nil)
  {
    NSData* imgdata = UIImageJPEGRepresentation(_image,1.0);
    [request setData:imgdata withFileName:@"1.png" andContentType:@"multipart/form-data" forKey:@"pic"];
  }
  [request startSynchronous];
  [request release];
}

//分享之后结果回调
-(void)requestFinished:(ASIHTTPRequest *)request
{
    NSLog(@"requestFinished %@",[request.responseString objectFromJSONString]);
    if ([delegate respondsToSelector:@selector(SinaWeiboDidShareSuccess:)]) {
        [delegate SinaWeiboDidShareSuccess:YES];
    }
}

-(void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"requestFailed %@",[request.responseString objectFromJSONString]);

    if ([delegate respondsToSelector:@selector(SinaWeiboDidShareSuccess:)]) {
        [delegate SinaWeiboDidShareSuccess:NO];
    }
}

#pragma mark -sinaAuthorizeDelegate  授权成功
-(void)sinaAuthorizeDelegateDidLogin:(NSDictionary *)dic
{
   self.accessToken = [dic objectForKey:@"access_token"];
   self.uid = [dic objectForKey:@"uid"];
   NSString *expires_in = [dic objectForKey:@"expires_in"];
   NSTimeInterval  expirationTime = [[NSDate date]timeIntervalSince1970]+[expires_in doubleValue];
  self.expirationDate = [NSDate dateWithTimeIntervalSince1970:expirationTime];
  
  if (self.accessToken&& 0 != [self.accessToken length])
  {
    //记录登陆后的数据信息
    NSMutableDictionary *oauthDic = [[NSMutableDictionary alloc]init];
    [oauthDic setObject:self.accessToken forKey:SINA_AccessToken];
    [oauthDic setObject:self.expirationDate forKey:SINA_ExpirationDate];
    [oauthDic setObject:self.uid forKey:SINA_Uid];
    [[NSUserDefaults standardUserDefaults]setObject:oauthDic forKey:SINA_OAuth];
    [oauthDic release];
  }
  if ([self.delegate respondsToSelector:@selector(SinaWeiboDidLogin:)]) {
    [delegate SinaWeiboDidLogin:self];
  }
}

#pragma mark－取消授权
-(void)sinaAuthorizeDelegateCancel
{
    if ([self.delegate respondsToSelector:@selector(SinaWeiboCancelLogin)]) {
        [delegate SinaWeiboCancelLogin];
    }
}
@end
